

#include <iostream>
#include <cmath>
#include <vector>
#include <iomanip>

#include "Exception.hpp"
#include "StationXvStore.hpp"
#include "Xvt.hpp"
#include "Vector.hpp"
#include "MJD.hpp"
#include "MiscMath.hpp"
#include "YDSTime.hpp"

using namespace gpstk;

#define debug 0

void StationXvStore::loadFile(std::string filename)
{
   ifstream input(filename.c_str());
   if (!input)
   {
      FileMissingException
      fe ( "Cannot Open xyz-formatted file: " + filename );
      GPSTK_THROW(fe);
   }
   
   bool ok(true);
   
   string line;
   
   while( input.peek() != EOF )
   {
      getline( input, line );

      if(debug)
          cout << "data line:" << line << endl;

      istringstream iss(line);

      string station;
      int year, doy;
      double second;
      double x, y, z, vx, vy, vz;
      iss >> station >> year >> doy >> second >> x >> y >> z >> vx >> vy >> vz;

      if(debug)
          cout << station << " "
               << year << " "
               << doy << " "
               << second << " "
               << x << " "
               << y << " "
               << z << " "
               << vx << " "
               << vy << " "
               << vz << " "
               << endl;


      YDSTime yds(year, doy, second);
      CommonTime epoch = yds.convertToCommonTime();
      
      Xvt xvt;
      xvt.x[0] = x;
      xvt.x[1] = y;
      xvt.x[2] = z;

      xvt.v[0] = vx;
      xvt.v[1] = vy;
      xvt.v[2] = vz;

      stationXvtData[station][epoch] = xvt;

   }
   
   input.close();
   
   if( !ok )
   {
      FileMissingException fe( filename + "is corrupted..." );
      GPSTK_THROW(fe);
   }
   
} // END of "loadPositionFile"


Triple StationXvStore::getPos(std::string station, CommonTime& t)
{

    t.setTimeSystem(TimeSystem::Unknown);

    Triple Pos;
    auto it = stationXvtData.find(station);
    if(it != stationXvtData.end())
    {
        epochXvtMap epochXvt;
        epochXvt = (*it).second;

        auto it = epochXvt.begin();

        CommonTime refEpoch = (*it).first;
        Xvt xvt = (*it).second;

        Triple pos = xvt.x;

        return pos;
    }
    else
    {
        InvalidRequest e(station + " not found.");
        GPSTK_THROW(e);
    }

} // END of "getPos"

Triple StationXvStore::getVel(std::string station, CommonTime& t)
{
    // to be extended.
}

